<template>
  <div class="user-relationship">
    <!-- 关系触发按钮 -->
    <div class="relationship-trigger">
      <button
        :class="relationshipStatus"
        :disabled="isProcessing"
        class="trigger-btn"
        @click="handleRelationshipAction"
      >
        <svg v-if="isProcessing" class="loading-spinner" fill="none" viewBox="0 0 24 24">
          <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
          <path d="M12 6v6l4 2" stroke="currentColor" stroke-width="2"/>
        </svg>

        <svg v-else-if="relationshipStatus === 'none'" fill="none" viewBox="0 0 24 24">
          <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
          <circle cx="8.5" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
          <line stroke="currentColor" stroke-width="2" x1="20" x2="20" y1="8" y2="14"/>
          <line stroke="currentColor" stroke-width="2" x1="23" x2="17" y1="11" y2="11"/>
        </svg>

        <svg v-else-if="relationshipStatus === 'pending_sent'" fill="none" viewBox="0 0 24 24">
          <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
          <polyline points="12,6 12,12 16,14" stroke="currentColor" stroke-width="2"/>
        </svg>

        <svg v-else-if="relationshipStatus === 'pending_received'" fill="none" viewBox="0 0 24 24">
          <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
          <circle cx="8.5" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
          <path d="M20 8v6M23 11l-3 3-3-3" stroke="currentColor" stroke-width="2"/>
        </svg>

        <svg v-else-if="relationshipStatus === 'connected'" fill="none" viewBox="0 0 24 24">
          <path d="M20 6L9 17l-5-5" stroke="currentColor" stroke-width="2"/>
        </svg>

        <svg v-else-if="relationshipStatus === 'blocked'" fill="none" viewBox="0 0 24 24">
          <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
          <line stroke="currentColor" stroke-width="2" x1="4.93" x2="19.07" y1="4.93" y2="19.07"/>
        </svg>

        <span>{{ getRelationshipText() }}</span>

        <!-- 下拉箭头（仅在已连接时显示） -->
        <svg v-if="relationshipStatus === 'connected'" class="dropdown-arrow" fill="none" viewBox="0 0 24 24">
          <polyline points="6,9 12,15 18,9" stroke="currentColor" stroke-width="2"/>
        </svg>
      </button>

      <!-- 关系操作菜单 -->
      <div v-if="showActionMenu" class="relationship-menu" @click.stop>
        <div v-if="relationshipStatus === 'connected'" class="menu-section">
          <h4 class="menu-title">管理关系</h4>

          <button class="menu-item" @click="viewProfile">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
              <circle cx="12" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
            </svg>
            查看资料
          </button>

          <button class="menu-item" @click="sendMessage">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" stroke="currentColor" stroke-width="2"/>
            </svg>
            发送消息
          </button>

          <button class="menu-item" @click="addToGroup">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
              <circle cx="9" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
              <path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75" stroke="currentColor" stroke-width="2"/>
            </svg>
            添加到群组
          </button>

          <hr class="menu-divider" />

          <button class="menu-item" @click="editRelationshipLabel">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z" stroke="currentColor" stroke-width="2"/>
              <line stroke="currentColor" stroke-width="2" x1="7" x2="7.01" y1="7" y2="7"/>
            </svg>
            编辑关系标签
          </button>

          <button class="menu-item" @click="adjustPrivacySettings">
            <svg fill="none" viewBox="0 0 24 24">
              <rect height="11" rx="2" ry="2" stroke="currentColor" stroke-width="2" width="18" x="3" y="11"/>
              <circle cx="12" cy="16" r="1" stroke="currentColor" stroke-width="2"/>
              <path d="M7 11V7a5 5 0 0 1 10 0v4" stroke="currentColor" stroke-width="2"/>
            </svg>
            隐私设置
          </button>

          <hr class="menu-divider" />

          <button class="menu-item danger" @click="showDisconnectConfirm">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
              <circle cx="8.5" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
              <line stroke="currentColor" stroke-width="2" x1="18" x2="23" y1="8" y2="13"/>
              <line stroke="currentColor" stroke-width="2" x1="23" x2="18" y1="8" y2="13"/>
            </svg>
            断开连接
          </button>

          <button class="menu-item danger" @click="blockUser">
            <svg fill="none" viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
              <line stroke="currentColor" stroke-width="2" x1="4.93" x2="19.07" y1="4.93" y2="19.07"/>
            </svg>
            屏蔽用户
          </button>
        </div>

        <div v-else-if="relationshipStatus === 'pending_received'" class="menu-section">
          <h4 class="menu-title">处理请求</h4>

          <button class="menu-item primary" @click="acceptRequest">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M20 6L9 17l-5-5" stroke="currentColor" stroke-width="2"/>
            </svg>
            接受请求
          </button>

          <button class="menu-item" @click="declineRequest">
            <svg fill="none" viewBox="0 0 24 24">
              <line stroke="currentColor" stroke-width="2" x1="18" x2="6" y1="6" y2="18"/>
              <line stroke="currentColor" stroke-width="2" x1="6" x2="18" y1="6" y2="18"/>
            </svg>
            拒绝请求
          </button>

          <button class="menu-item danger" @click="blockUser">
            <svg fill="none" viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
              <line stroke="currentColor" stroke-width="2" x1="4.93" x2="19.07" y1="4.93" y2="19.07"/>
            </svg>
            屏蔽并拒绝
          </button>
        </div>
      </div>
    </div>

    <!-- 关系详情面板 -->
    <div v-if="showRelationshipDetail" class="relationship-detail" @click.stop>
      <div class="detail-header">
        <div class="user-info">
          <div class="user-avatar">
            <img v-if="targetUser.avatar" :alt="targetUser.name" :src="targetUser.avatar" />
            <div v-else class="avatar-placeholder">
              {{ targetUser.name.charAt(0) }}
            </div>
            <div v-if="targetUser.isOnline" class="online-indicator"></div>
          </div>

          <div class="user-details">
            <h3 class="user-name">{{ targetUser.name }}</h3>
            <div class="user-status">
              <span class="relationship-label">{{ relationship?.label || getDefaultRelationLabel() }}</span>
              <span class="connection-time">{{ formatConnectionTime() }}</span>
            </div>
          </div>
        </div>

        <button class="close-detail" @click="closeRelationshipDetail">
          <svg fill="none" viewBox="0 0 24 24">
            <line stroke="currentColor" stroke-width="2" x1="18" x2="6" y1="6" y2="18"/>
            <line stroke="currentColor" stroke-width="2" x1="6" x2="18" y1="6" y2="18"/>
          </svg>
        </button>
      </div>

      <div class="detail-content">
        <!-- 关系统计 -->
        <div class="relationship-stats">
          <div class="stat-item">
            <div class="stat-number">{{ mutualConnections }}</div>
            <div class="stat-label">共同联系人</div>
          </div>

          <div class="stat-item">
            <div class="stat-number">{{ sharedActivities }}</div>
            <div class="stat-label">共同活动</div>
          </div>

          <div class="stat-item">
            <div class="stat-number">{{ interactionCount }}</div>
            <div class="stat-label">互动次数</div>
          </div>
        </div>

        <!-- 关系时间线 -->
        <div class="relationship-timeline">
          <h4 class="timeline-title">关系时间线</h4>

          <div class="timeline-list">
            <div v-for="event in relationshipEvents" :key="event.id" class="timeline-item">
              <div :class="event.type" class="timeline-dot"></div>
              <div class="timeline-content">
                <div class="timeline-header">
                  <span class="timeline-action">{{ event.action }}</span>
                  <span class="timeline-time">{{ formatTimelineDate(event.timestamp) }}</span>
                </div>
                <div v-if="event.description" class="timeline-description">
                  {{ event.description }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 共同联系人 -->
        <div v-if="mutualConnectionsList.length > 0" class="mutual-connections">
          <h4 class="section-title">共同联系人 ({{ mutualConnections }})</h4>

          <div class="connections-grid">
            <div v-for="connection in mutualConnectionsList" :key="connection.id" class="connection-item">
              <div class="connection-avatar">
                <img v-if="connection.avatar" :alt="connection.name" :src="connection.avatar" />
                <div v-else class="avatar-placeholder">
                  {{ connection.name.charAt(0) }}
                </div>
              </div>
              <div class="connection-name">{{ connection.name }}</div>
            </div>
          </div>

          <button v-if="mutualConnections > mutualConnectionsList.length" class="view-all-btn">
            查看全部 {{ mutualConnections }} 个共同联系人
          </button>
        </div>

        <!-- 隐私设置 -->
        <div class="privacy-settings">
          <h4 class="section-title">隐私设置</h4>

          <div class="privacy-options">
            <label class="privacy-option">
              <input
                v-model="privacySettings.allowViewProfile"
                type="checkbox"
                @change="updatePrivacySettings"
              />
              <span class="checkbox-custom"></span>
              <div class="option-info">
                <span class="option-title">允许查看我的资料</span>
                <span class="option-desc">对方可以查看您的个人资料详情</span>
              </div>
            </label>

            <label class="privacy-option">
              <input
                v-model="privacySettings.allowViewActivities"
                type="checkbox"
                @change="updatePrivacySettings"
              />
              <span class="checkbox-custom"></span>
              <div class="option-info">
                <span class="option-title">允许查看我的活动</span>
                <span class="option-desc">对方可以查看您参与的活动</span>
              </div>
            </label>

            <label class="privacy-option">
              <input
                v-model="privacySettings.allowViewMedia"
                type="checkbox"
                @change="updatePrivacySettings"
              />
              <span class="checkbox-custom"></span>
              <div class="option-info">
                <span class="option-title">允许查看我的媒体</span>
                <span class="option-desc">对方可以查看您上传的照片和视频</span>
              </div>
            </label>

            <label class="privacy-option">
              <input
                v-model="privacySettings.allowDirectMessage"
                type="checkbox"
                @change="updatePrivacySettings"
              />
              <span class="checkbox-custom"></span>
              <div class="option-info">
                <span class="option-title">允许发送消息</span>
                <span class="option-desc">对方可以直接向您发送私信</span>
              </div>
            </label>
          </div>
        </div>
      </div>
    </div>

    <!-- 确认对话框 -->
    <div v-if="showConfirmDialog" class="confirm-overlay" @click.self="closeConfirmDialog">
      <div class="confirm-dialog">
        <div class="confirm-header">
          <h3>{{ confirmDialog.title }}</h3>
        </div>

        <div class="confirm-body">
          <p>{{ confirmDialog.message }}</p>
          <div v-if="confirmDialog.warning" class="confirm-warning">
            <svg fill="none" viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
              <line stroke="currentColor" stroke-width="2" x1="12" x2="12" y1="8" y2="12"/>
              <line stroke="currentColor" stroke-width="2" x1="12" x2="12.01" y1="16" y2="16"/>
            </svg>
            {{ confirmDialog.warning }}
          </div>
        </div>

        <div class="confirm-footer">
          <button class="confirm-btn secondary" @click="closeConfirmDialog">
            取消
          </button>
          <button
            :class="{ 'danger': confirmDialog.type === 'danger' }"
            :disabled="isProcessing"
            class="confirm-btn primary"
            @click="executeConfirmedAction"
          >
            <svg v-if="isProcessing" class="loading-spinner" fill="none" viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
              <path d="M12 6v6l4 2" stroke="currentColor" stroke-width="2"/>
            </svg>
            {{ isProcessing ? '处理中...' : confirmDialog.confirmText }}
          </button>
        </div>
      </div>
    </div>

    <!-- 关系标签编辑器 -->
    <div v-if="showLabelEditor" class="label-editor-overlay" @click.self="closeLabelEditor">
      <div class="label-editor">
        <div class="editor-header">
          <h3>编辑关系标签</h3>
          <button class="close-btn" @click="closeLabelEditor">
            <svg fill="none" viewBox="0 0 24 24">
              <line stroke="currentColor" stroke-width="2" x1="18" x2="6" y1="6" y2="18"/>
              <line stroke="currentColor" stroke-width="2" x1="6" x2="18" y1="6" y2="18"/>
            </svg>
          </button>
        </div>

        <div class="editor-content">
          <div class="current-user-info">
            <div class="user-avatar">
              <img v-if="targetUser.avatar" :alt="targetUser.name" :src="targetUser.avatar" />
              <div v-else class="avatar-placeholder">
                {{ targetUser.name.charAt(0) }}
              </div>
            </div>
            <span class="user-name">{{ targetUser.name }}</span>
          </div>

          <div class="label-input-section">
            <label class="input-label">关系标签</label>
            <input
              v-model="editingLabel"
              class="label-input"
              maxlength="20"
              placeholder="例如：家人、朋友、同事..."
              type="text"
              @keyup.enter="saveRelationshipLabel"
            />
            <div class="input-hint">{{ editingLabel.length }}/20</div>
          </div>

          <div class="preset-labels">
            <h4>常用标签</h4>
            <div class="preset-grid">
              <button
                v-for="preset in presetLabels"
                :key="preset"
                :class="{ 'active': editingLabel === preset }"
                class="preset-btn"
                @click="editingLabel = preset"
              >
                {{ preset }}
              </button>
            </div>
          </div>
        </div>

        <div class="editor-footer">
          <button class="editor-btn secondary" @click="closeLabelEditor">
            取消
          </button>
          <button :disabled="!editingLabel.trim()" class="editor-btn primary" @click="saveRelationshipLabel">
            保存
          </button>
        </div>
      </div>
    </div>

    <!-- 背景遮罩 -->
    <div v-if="showActionMenu || showRelationshipDetail" class="relationship-backdrop" @click="closeAllPanels"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { Notify } from '@opentiny/vue'

// Props
interface Props {
  userId: number
  initialStatus?: RelationshipStatus
  showDetailPanel?: boolean
  compact?: boolean
}

type RelationshipStatus = 'none' | 'pending_sent' | 'pending_received' | 'connected' | 'blocked'

interface User {
  id: number
  name: string
  avatar?: string
  isOnline?: boolean
}

interface Relationship {
  id: number
  userId: number
  targetUserId: number
  status: RelationshipStatus
  label?: string
  createdAt: string
  updatedAt: string
}

interface RelationshipEvent {
  id: number
  type: 'connected' | 'label_changed' | 'privacy_updated' | 'interaction'
  action: string
  description?: string
  timestamp: string
}

const props = withDefaults(defineProps<Props>(), {
  initialStatus: 'none',
  showDetailPanel: false,
  compact: false
})

// Emits
const emit = defineEmits<{
  'relationship-changed': [status: RelationshipStatus, relationship?: Relationship]
  'user-blocked': [userId: number]
  'user-unblocked': [userId: number]
  'message-sent': [userId: number]
  'profile-viewed': [userId: number]
}>()

// 响应式数据
const relationshipStatus = ref<RelationshipStatus>(props.initialStatus)
const isProcessing = ref(false)
const showActionMenu = ref(false)
const showRelationshipDetail = ref(false)
const showConfirmDialog = ref(false)
const showLabelEditor = ref(false)

const relationship = ref<Relationship | null>(null)
const targetUser = ref<User>({
  id: props.userId,
  name: '用户',
  avatar: '',
  isOnline: false
})

const mutualConnections = ref(0)
const sharedActivities = ref(0)
const interactionCount = ref(0)
const mutualConnectionsList = ref<User[]>([])
const relationshipEvents = ref<RelationshipEvent[]>([])

const editingLabel = ref('')
const presetLabels = ['家人', '朋友', '同事', '同学', '邻居', '合作伙伴', '老师', '学生']

const privacySettings = ref({
  allowViewProfile: true,
  allowViewActivities: true,
  allowViewMedia: true,
  allowDirectMessage: true
})

const confirmDialog = ref({
  title: '',
  message: '',
  warning: '',
  confirmText: '',
  type: 'default',
  action: () => {}
})

// 计算属性
const getRelationshipText = () => {
  switch (relationshipStatus.value) {
    case 'none':
      return '添加联系人'
    case 'pending_sent':
      return '请求已发送'
    case 'pending_received':
      return '接受请求'
    case 'connected':
      return '已连接'
    case 'blocked':
      return '已屏蔽'
    default:
      return '添加联系人'
  }
}

const getDefaultRelationLabel = () => {
  switch (relationshipStatus.value) {
    case 'connected':
      return relationship.value?.label || '联系人'
    default:
      return '用户'
  }
}

// 方法
const handleRelationshipAction = () => {
  switch (relationshipStatus.value) {
    case 'none':
      sendConnectionRequest()
      break
    case 'pending_sent':
      cancelConnectionRequest()
      break
    case 'pending_received':
      showActionMenu.value = !showActionMenu.value
      break
    case 'connected':
      showActionMenu.value = !showActionMenu.value
      break
    case 'blocked':
      unblockUser()
      break
  }
}

const sendConnectionRequest = async () => {
  if (isProcessing.value) return

  try {
    isProcessing.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    relationshipStatus.value = 'pending_sent'

    Notify({
      type: 'success',
      message: '连接请求已发送',
      position: 'top-right'
    })

    emit('relationship-changed', relationshipStatus.value)

  } catch (error) {
    console.error('Send connection request failed:', error)
    Notify({
      type: 'error',
      message: '发送请求失败，请重试',
      position: 'top-right'
    })
  } finally {
    isProcessing.value = false
  }
}

const cancelConnectionRequest = async () => {
  if (isProcessing.value) return

  try {
    isProcessing.value = true

    await new Promise(resolve => setTimeout(resolve, 500))

    relationshipStatus.value = 'none'

    Notify({
      type: 'success',
      message: '连接请求已取消',
      position: 'top-right'
    })

    emit('relationship-changed', relationshipStatus.value)

  } catch (error) {
    console.error('Cancel connection request failed:', error)
    Notify({
      type: 'error',
      message: '取消请求失败',
      position: 'top-right'
    })
  } finally {
    isProcessing.value = false
  }
}

const acceptRequest = async () => {
  if (isProcessing.value) return

  try {
    isProcessing.value = true

    await new Promise(resolve => setTimeout(resolve, 1000))

    relationshipStatus.value = 'connected'
    relationship.value = {
      id: Date.now(),
      userId: 1,
      targetUserId: props.userId,
      status: 'connected',
      label: '联系人',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }

    showActionMenu.value = false
    loadRelationshipData()

    Notify({
      type: 'success',
      message: '连接请求已接受',
      position: 'top-right'
    })

    emit('relationship-changed', relationshipStatus.value, relationship.value)

  } catch (error) {
    console.error('Accept request failed:', error)
    Notify({
      type: 'error',
      message: '接受请求失败',
      position: 'top-right'
    })
  } finally {
    isProcessing.value = false
  }
}

const declineRequest = async () => {
  if (isProcessing.value) return

  try {
    isProcessing.value = true

    await new Promise(resolve => setTimeout(resolve, 500))

    relationshipStatus.value = 'none'
    showActionMenu.value = false

    Notify({
      type: 'success',
      message: '连接请求已拒绝',
      position: 'top-right'
    })

    emit('relationship-changed', relationshipStatus.value)

  } catch (error) {
    console.error('Decline request failed:', error)
    Notify({
      type: 'error',
      message: '拒绝请求失败',
      position: 'top-right'
    })
  } finally {
    isProcessing.value = false
  }
}

const showDisconnectConfirm = () => {
  confirmDialog.value = {
    title: '断开连接',
    message: `确定要与 ${targetUser.value.name} 断开连接吗？`,
    warning: '断开连接后，您将无法查看对方的活动和媒体内容。',
    confirmText: '断开连接',
    type: 'danger',
    action: disconnectUser
  }

  showConfirmDialog.value = true
  showActionMenu.value = false
}

const disconnectUser = async () => {
  if (isProcessing.value) return

  try {
    isProcessing.value = true

    await new Promise(resolve => setTimeout(resolve, 1000))

    relationshipStatus.value = 'none'
    relationship.value = null
    showConfirmDialog.value = false

    Notify({
      type: 'success',
      message: '已断开连接',
      position: 'top-right'
    })

    emit('relationship-changed', relationshipStatus.value)

  } catch (error) {
    console.error('Disconnect user failed:', error)
    Notify({
      type: 'error',
      message: '断开连接失败',
      position: 'top-right'
    })
  } finally {
    isProcessing.value = false
  }
}

const blockUser = async () => {
  if (isProcessing.value) return

  try {
    isProcessing.value = true

    await new Promise(resolve => setTimeout(resolve, 800))

    relationshipStatus.value = 'blocked'
    showActionMenu.value = false
    showConfirmDialog.value = false

    Notify({
      type: 'success',
      message: '用户已屏蔽',
      position: 'top-right'
    })

    emit('user-blocked', props.userId)
    emit('relationship-changed', relationshipStatus.value)

  } catch (error) {
    console.error('Block user failed:', error)
    Notify({
      type: 'error',
      message: '屏蔽用户失败',
      position: 'top-right'
    })
  } finally {
    isProcessing.value = false
  }
}

const unblockUser = async () => {
  if (isProcessing.value) return

  try {
    isProcessing.value = true

    await new Promise(resolve => setTimeout(resolve, 500))

    relationshipStatus.value = 'none'

    Notify({
      type: 'success',
      message: '用户已解除屏蔽',
      position: 'top-right'
    })

    emit('user-unblocked', props.userId)
    emit('relationship-changed', relationshipStatus.value)

  } catch (error) {
    console.error('Unblock user failed:', error)
    Notify({
      type: 'error',
      message: '解除屏蔽失败',
      position: 'top-right'
    })
  } finally {
    isProcessing.value = false
  }
}

const viewProfile = () => {
  showActionMenu.value = false
  emit('profile-viewed', props.userId)
}

const sendMessage = () => {
  showActionMenu.value = false
  emit('message-sent', props.userId)
}

const addToGroup = () => {
  showActionMenu.value = false
  // 实现添加到群组功能
  Notify({
    type: 'info',
    message: '添加到群组功能开发中',
    position: 'top-right'
  })
}

const editRelationshipLabel = () => {
  editingLabel.value = relationship.value?.label || ''
  showLabelEditor.value = true
  showActionMenu.value = false
}

const saveRelationshipLabel = async () => {
  if (!editingLabel.value.trim()) return

  try {
    isProcessing.value = true

    await new Promise(resolve => setTimeout(resolve, 500))

    if (relationship.value) {
      relationship.value.label = editingLabel.value.trim()
      relationship.value.updatedAt = new Date().toISOString()
    }

    showLabelEditor.value = false

    Notify({
      type: 'success',
      message: '关系标签已更新',
      position: 'top-right'
    })

  } catch (error) {
    console.error('Save relationship label failed:', error)
    Notify({
      type: 'error',
      message: '更新标签失败',
      position: 'top-right'
    })
  } finally {
    isProcessing.value = false
  }
}

const adjustPrivacySettings = () => {
  showRelationshipDetail.value = true
  showActionMenu.value = false
}

const updatePrivacySettings = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))

    Notify({
      type: 'success',
      message: '隐私设置已更新',
      position: 'top-right'
    })

  } catch (error) {
    console.error('Update privacy settings failed:', error)
    Notify({
      type: 'error',
      message: '更新设置失败',
      position: 'top-right'
    })
  }
}

const loadRelationshipData = async () => {
  try {
    // 模拟加载关系数据
    await new Promise(resolve => setTimeout(resolve, 500))

    // 模拟数据
    targetUser.value = {
      id: props.userId,
      name: '张小明',
      avatar: '/images/avatars/user2.jpg',
      isOnline: true
    }

    mutualConnections.value = 12
    sharedActivities.value = 8
    interactionCount.value = 156

    mutualConnectionsList.value = [
      { id: 3, name: '李小红', avatar: '/images/avatars/user3.jpg' },
      { id: 4, name: '王大华', avatar: '/images/avatars/user4.jpg' },
      { id: 5, name: '刘小芳', avatar: '/images/avatars/user5.jpg' }
    ]

    relationshipEvents.value = [
      {
        id: 1,
        type: 'connected',
        action: '建立连接',
        description: '您与张小明成为了联系人',
        timestamp: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
      },
      {
        id: 2,
        type: 'interaction',
        action: '参与活动',
        description: '一起参加了"家庭聚餐"活动',
        timestamp: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString()
      },
      {
        id: 3,
        type: 'label_changed',
        action: '更新标签',
        description: '关系标签更改为"家人"',
        timestamp: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString()
      }
    ]

  } catch (error) {
    console.error('Load relationship data failed:', error)
  }
}

const closeAllPanels = () => {
  showActionMenu.value = false
  showRelationshipDetail.value = false
}

const closeRelationshipDetail = () => {
  showRelationshipDetail.value = false
}

const closeConfirmDialog = () => {
  showConfirmDialog.value = false
}

const closeLabelEditor = () => {
  showLabelEditor.value = false
  editingLabel.value = ''
}

const executeConfirmedAction = () => {
  confirmDialog.value.action()
}

const formatConnectionTime = (): string => {
  if (!relationship.value) return ''

  const date = new Date(relationship.value.createdAt)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    return '今天建立连接'
  } else if (diffDays === 1) {
    return '昨天建立连接'
  } else if (diffDays < 30) {
    return `${diffDays}天前建立连接`
  } else if (diffDays < 365) {
    const months = Math.floor(diffDays / 30)
    return `${months}个月前建立连接`
  } else {
    const years = Math.floor(diffDays / 365)
    return `${years}年前建立连接`
  }
}

const formatTimelineDate = (timestamp: string): string => {
  const date = new Date(timestamp)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

// 监听器
watch(() => props.initialStatus, (newStatus) => {
  relationshipStatus.value = newStatus
})

watch(() => props.showDetailPanel, (show) => {
  if (show) {
    showRelationshipDetail.value = true
    loadRelationshipData()
  }
})

// 生命周期
onMounted(() => {
  if (relationshipStatus.value === 'connected') {
    loadRelationshipData()
  }

  // 点击外部关闭菜单
  document.addEventListener('click', (e) => {
    if (!(e.target as Element).closest('.user-relationship')) {
      showActionMenu.value = false
    }
  })
})

onUnmounted(() => {
  // 清理事件监听器
})

// 暴露给父组件的方法
defineExpose({
  refreshRelationship: loadRelationshipData,
  openDetailPanel: () => {
    showRelationshipDetail.value = true
    loadRelationshipData()
  },
  closeDetailPanel: () => {
    showRelationshipDetail.value = false
  }
})
</script>

<style lang="scss" scoped>
.user-relationship {
  position: relative;

  .relationship-trigger {
    .trigger-btn {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.5rem 1rem;
      border-radius: 8px;
      border: none;
      cursor: pointer;
      font-size: 0.85rem;
      font-weight: 500;
      transition: all 0.2s ease;

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }

      svg {
        width: 16px;
        height: 16px;
      }

      .loading-spinner {
        animation: spin 1s linear infinite;
      }

      .dropdown-arrow {
        width: 12px;
        height: 12px;
        margin-left: 0.25rem;
        opacity: 0.6;
      }

      // 状态样式
      &.none {
        background: #3b82f6;
        color: white;

        &:hover:not(:disabled) {
          background: #2563eb;
        }
      }

      &.pending_sent {
        background: #f59e0b;
        color: white;

        &:hover:not(:disabled) {
          background: #d97706;
        }
      }

      &.pending_received {
        background: #10b981;
        color: white;

        &:hover:not(:disabled) {
          background: #059669;
        }
      }

      &.connected {
        background: #f3f4f6;
        color: #374151;
        border: 1px solid #d1d5db;

        &:hover:not(:disabled) {
          background: #e5e7eb;
          border-color: #9ca3af;
        }
      }

      &.blocked {
        background: #ef4444;
        color: white;

        &:hover:not(:disabled) {
          background: #dc2626;
        }
      }
    }

    .relationship-menu {
      position: absolute;
      top: calc(100% + 0.5rem);
      left: 0;
      background: white;
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      z-index: 20;
      min-width: 200px;
      overflow: hidden;
      animation: slideDown 0.2s ease-out;

      .menu-section {
        padding: 0.75rem 0;

        .menu-title {
          padding: 0.5rem 1rem;
          margin: 0 0 0.5rem 0;
          font-size: 0.8rem;
          font-weight: 600;
          color: #6b7280;
          text-transform: uppercase;
          letter-spacing: 0.025em;
          border-bottom: 1px solid #f1f5f9;
        }

        .menu-item {
          display: flex;
          align-items: center;
          gap: 0.75rem;
          width: 100%;
          padding: 0.75rem 1rem;
          border: none;
          background: none;
          text-align: left;
          color: #374151;
          cursor: pointer;
          font-size: 0.85rem;
          transition: background 0.2s ease;

          &:hover {
            background: #f9fafb;
          }

          &.primary {
            color: #059669;

            &:hover {
              background: #ecfdf5;
            }
          }

          &.danger {
            color: #ef4444;

            &:hover {
              background: #fef2f2;
            }
          }

          svg {
            width: 16px;
            height: 16px;
            flex-shrink: 0;
          }
        }

        .menu-divider {
          border: none;
          border-top: 1px solid #f1f5f9;
          margin: 0.5rem 0;
        }
      }
    }
  }

  .relationship-detail {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
    z-index: 50;
    width: 500px;
    max-width: 90vw;
    max-height: 90vh;
    overflow: hidden;
    animation: slideUp 0.3s ease-out;

    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 1.5rem;
      border-bottom: 1px solid #f1f5f9;
      background: #f8fafc;

      .user-info {
        display: flex;
        gap: 1rem;

        .user-avatar {
          position: relative;
          width: 60px;
          height: 60px;
          border-radius: 50%;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .avatar-placeholder {
            width: 100%;
            height: 100%;
            background: #e5e7eb;
            color: #6b7280;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 1.5rem;
          }

          .online-indicator {
            position: absolute;
            bottom: 4px;
            right: 4px;
            width: 14px;
            height: 14px;
            background: #10b981;
            border: 3px solid white;
            border-radius: 50%;
          }
        }

        .user-details {
          .user-name {
            margin: 0 0 0.5rem 0;
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
          }

          .user-status {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;

            .relationship-label {
              padding: 0.25rem 0.5rem;
              background: #dbeafe;
              color: #1d4ed8;
              border-radius: 12px;
              font-size: 0.75rem;
              font-weight: 500;
              width: fit-content;
            }

            .connection-time {
              font-size: 0.8rem;
              color: #6b7280;
            }
          }
        }
      }

      .close-detail {
        width: 32px;
        height: 32px;
        border: none;
        background: transparent;
        color: #9ca3af;
        cursor: pointer;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s ease;

        &:hover {
          background: #f3f4f6;
          color: #6b7280;
        }

        svg {
          width: 16px;
          height: 16px;
        }
      }
    }

    .detail-content {
      max-height: calc(90vh - 120px);
      overflow-y: auto;

      .relationship-stats {
        display: flex;
        padding: 1.5rem;
        border-bottom: 1px solid #f8fafc;

        .stat-item {
          flex: 1;
          text-align: center;

          .stat-number {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
          }

          .stat-label {
            font-size: 0.8rem;
            color: #6b7280;
          }
        }
      }

      .relationship-timeline {
        padding: 1.5rem;
        border-bottom: 1px solid #f8fafc;

        .timeline-title {
          margin: 0 0 1rem 0;
          font-size: 1rem;
          font-weight: 600;
          color: #374151;
        }

        .timeline-list {
          .timeline-item {
            display: flex;
            gap: 0.75rem;
            margin-bottom: 1rem;

            &:last-child {
              margin-bottom: 0;
            }

            .timeline-dot {
              width: 12px;
              height: 12px;
              border-radius: 50%;
              margin-top: 0.25rem;
              flex-shrink: 0;

              &.connected {
                background: #10b981;
              }

              &.interaction {
                background: #3b82f6;
              }

              &.label_changed {
                background: #f59e0b;
              }
            }

            .timeline-content {
              flex: 1;

              .timeline-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 0.25rem;

                .timeline-action {
                  font-weight: 500;
                  color: #374151;
                  font-size: 0.9rem;
                }

                .timeline-time {
                  font-size: 0.8rem;
                  color: #9ca3af;
                }
              }

              .timeline-description {
                font-size: 0.85rem;
                color: #6b7280;
                line-height: 1.4;
              }
            }
          }
        }
      }

      .mutual-connections {
        padding: 1.5rem;
        border-bottom: 1px solid #f8fafc;

        .section-title {
          margin: 0 0 1rem 0;
          font-size: 1rem;
          font-weight: 600;
          color: #374151;
        }

        .connections-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
          gap: 1rem;
          margin-bottom: 1rem;

          .connection-item {
            text-align: center;

            .connection-avatar {
              width: 50px;
              height: 50px;
              border-radius: 50%;
              overflow: hidden;
              margin: 0 auto 0.5rem;

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }

              .avatar-placeholder {
                width: 100%;
                height: 100%;
                background: #e5e7eb;
                color: #6b7280;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: 600;
              }
            }

            .connection-name {
              font-size: 0.8rem;
              color: #374151;
              font-weight: 500;
            }
          }
        }

        .view-all-btn {
          width: 100%;
          padding: 0.5rem;
          background: #f3f4f6;
          border: none;
          border-radius: 6px;
          color: #6b7280;
          cursor: pointer;
          font-size: 0.85rem;
          transition: all 0.2s ease;

          &:hover {
            background: #e5e7eb;
            color: #374151;
          }
        }
      }

      .privacy-settings {
        padding: 1.5rem;

        .section-title {
          margin: 0 0 1rem 0;
          font-size: 1rem;
          font-weight: 600;
          color: #374151;
        }

        .privacy-options {
          display: flex;
          flex-direction: column;
          gap: 1rem;

          .privacy-option {
            display: flex;
            align-items: flex-start;
            gap: 0.75rem;
            cursor: pointer;

            input[type="checkbox"] {
              display: none;
            }

            .checkbox-custom {
              width: 18px;
              height: 18px;
              border: 2px solid #d1d5db;
              border-radius: 4px;
              position: relative;
              margin-top: 0.125rem;
              flex-shrink: 0;
              transition: all 0.2s ease;

              &::after {
                content: '✓';
                position: absolute;
                inset: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                font-size: 12px;
                font-weight: bold;
                opacity: 0;
                transition: opacity 0.2s ease;
              }
            }

            input:checked + .checkbox-custom {
              background: #3b82f6;
              border-color: #3b82f6;

              &::after {
                opacity: 1;
              }
            }

            .option-info {
              display: flex;
              flex-direction: column;
              gap: 0.25rem;

              .option-title {
                font-size: 0.9rem;
                font-weight: 500;
                color: #374151;
              }

              .option-desc {
                font-size: 0.8rem;
                color: #6b7280;
                line-height: 1.4;
              }
            }
          }
        }
      }
    }
  }

  .confirm-overlay,
  .label-editor-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 60;

    .confirm-dialog,
    .label-editor {
      background: white;
      border-radius: 12px;
      min-width: 400px;
      max-width: 90vw;
      animation: scaleIn 0.2s ease-out;

      .confirm-header,
      .editor-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.5rem 1.5rem 1rem;

        h3 {
          margin: 0;
          font-size: 1.1rem;
          font-weight: 600;
          color: #1e293b;
        }

        .close-btn {
          width: 32px;
          height: 32px;
          border: none;
          background: transparent;
          color: #9ca3af;
          cursor: pointer;
          border-radius: 6px;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.2s ease;

          &:hover {
            background: #f3f4f6;
            color: #6b7280;
          }

          svg {
            width: 16px;
            height: 16px;
          }
        }
      }

      .confirm-body,
      .editor-content {
        padding: 0 1.5rem 1rem;

        p {
          margin: 0 0 1rem 0;
          color: #374151;
          line-height: 1.5;
        }

        .confirm-warning {
          display: flex;
          align-items: flex-start;
          gap: 0.75rem;
          padding: 1rem;
          background: #fef3c7;
          border: 1px solid #f59e0b;
          border-radius: 8px;
          font-size: 0.9rem;
          color: #92400e;

          svg {
            width: 20px;
            height: 20px;
            flex-shrink: 0;
            margin-top: 0.125rem;
          }
        }
      }

      .confirm-footer,
      .editor-footer {
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
        padding: 1rem 1.5rem 1.5rem;

        .confirm-btn,
        .editor-btn {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          padding: 0.5rem 1rem;
          border-radius: 6px;
          border: none;
          cursor: pointer;
          font-size: 0.85rem;
          font-weight: 500;
          transition: all 0.2s ease;

          &:disabled {
            opacity: 0.6;
            cursor: not-allowed;
          }

          svg {
            width: 14px;
            height: 14px;
          }

          .loading-spinner {
            animation: spin 1s linear infinite;
          }

          &.secondary {
            background: #f3f4f6;
            color: #374151;

            &:hover:not(:disabled) {
              background: #e5e7eb;
            }
          }

          &.primary {
            background: #3b82f6;
            color: white;

            &:hover:not(:disabled) {
              background: #2563eb;
            }

            &.danger {
              background: #ef4444;

              &:hover:not(:disabled) {
                background: #dc2626;
              }
            }
          }
        }
      }
    }

    .label-editor {
      .editor-content {
        .current-user-info {
          display: flex;
          align-items: center;
          gap: 0.75rem;
          margin-bottom: 1.5rem;
          padding: 1rem;
          background: #f8fafc;
          border: 1px solid #e2e8f0;
          border-radius: 8px;

          .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }

            .avatar-placeholder {
              width: 100%;
              height: 100%;
              background: #e5e7eb;
              color: #6b7280;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: 600;
            }
          }

          .user-name {
            font-weight: 500;
            color: #374151;
          }
        }

        .label-input-section {
          margin-bottom: 1.5rem;

          .input-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #374151;
            font-size: 0.9rem;
          }

          .label-input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 0.9rem;
            transition: border-color 0.2s ease;

            &:focus {
              outline: none;
              border-color: #3b82f6;
              box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            }
          }

          .input-hint {
            margin-top: 0.25rem;
            font-size: 0.75rem;
            color: #9ca3af;
            text-align: right;
          }
        }

        .preset-labels {
          h4 {
            margin: 0 0 0.75rem 0;
            font-size: 0.9rem;
            font-weight: 600;
            color: #374151;
          }

          .preset-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
            gap: 0.5rem;

            .preset-btn {
              padding: 0.5rem 0.75rem;
              background: #f3f4f6;
              border: 1px solid #d1d5db;
              border-radius: 6px;
              color: #374151;
              cursor: pointer;
              font-size: 0.8rem;
              text-align: center;
              transition: all 0.2s ease;

              &:hover {
                background: #e5e7eb;
                border-color: #9ca3af;
              }

              &.active {
                background: #3b82f6;
                border-color: #3b82f6;
                color: white;
              }
            }
          }
        }
      }
    }
  }

  .relationship-backdrop {
    position: fixed;
    inset: 0;
    background: transparent;
    z-index: 10;
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translate(-50%, -45%);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-relationship {
    .relationship-detail {
      width: 100vw;
      height: 100vh;
      max-width: none;
      max-height: none;
      top: 0 !important;
      left: 0 !important;
      transform: none !important;
      border-radius: 0;

      .detail-header {
        padding: 1rem;

        .user-info {
          flex-direction: column;
          gap: 0.75rem;
          text-align: center;
        }
      }

      .detail-content {
        max-height: calc(100vh - 120px);

        .connections-grid {
          grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
        }
      }
    }

    .confirm-overlay .confirm-dialog,
    .label-editor-overlay .label-editor {
      min-width: 90vw;
      margin: 1rem;
    }
  }
}

// 暗色模式
@media (prefers-color-scheme: dark) {
  .user-relationship {
    .relationship-menu,
    .relationship-detail,
    .confirm-dialog,
    .label-editor {
      background: #1f2937;
      border-color: #374151;

      .menu-title,
      .section-title,
      .timeline-title,
      h3 {
        color: #f9fafb;
      }

      .menu-item,
      .option-title,
      .timeline-action,
      .user-name,
      .input-label,
      p {
        color: #d1d5db;
      }

      .detail-header,
      .confirm-header,
      .editor-header {
        background: #111827;
        border-bottom-color: #374151;
      }

      .privacy-option input:checked + .checkbox-custom {
        background: #3b82f6;
      }
    }
  }
}
</style>
